package com.meet.bizservice.impl;

import com.meet.persist.dao.FileUploadDao;
import com.meet.api.dto.response.MeetFileUploadResponseDTO;
import com.meet.persist.entity.FileUpload;
import com.meet.exception.BusinessException;
import com.meet.bizservice.FileUploadService;
import com.meet.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    private static final Logger logger = LoggerFactory.getLogger(FileUploadServiceImpl.class);

    @Autowired
    private FileUploadDao fileUploadDao;

    @Override
    public Result<MeetFileUploadResponseDTO> uploadImage(MultipartFile file) {

        try {
            logger.info("Starting file upload for file: {}", file.getOriginalFilename());

            if (file.isEmpty()) {
                logger.warn("File upload failed - file is empty");
                return Result.error("文件不能为空");
            }

            // 生成文件ID
            String fileId = UUID.randomUUID().toString().replace("-", "");

            // 创建文件上传记录
            FileUpload fileUpload = new FileUpload();
            fileUpload.setFileId(fileId);
            fileUpload.setOriginalName(file.getOriginalFilename());
            fileUpload.setFileSize((int) file.getSize());
            fileUpload.setFileType(file.getContentType());
            fileUpload.setUploaderId("1234567890"); // 这里应该从JWT中获取用户ID

            // 保存文件到本地（实际项目中可能需要上传到云存储）
            String filePath = "/tmp/" + fileId;
            File destFile = new File(filePath);

            // 确保目录存在
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }

            file.transferTo(destFile);

            // 设置文件路径和URL
            fileUpload.setFilePath(filePath);
            fileUpload.setFileUrl("http://localhost:8080/files/" + fileId);

            // 保存到数据库
            if (fileUploadDao.insert(fileUpload)) {
                logger.info("File uploaded successfully with ID: {}", fileId);

                MeetFileUploadResponseDTO fileUploadDTO = convertToDTO(fileUpload);
                return Result.success(fileUploadDTO);
            } else {
                logger.error("Failed to save file upload record to database");
                return Result.error("文件上传失败");
            }

        } catch (Exception e) {
            logger.error("Error during file upload", e);
            throw new BusinessException("文件上传失败");
        }
    }

    private MeetFileUploadResponseDTO convertToDTO(FileUpload fileUpload) {

        if (fileUpload == null) {
            return null;
        }

        MeetFileUploadResponseDTO dto = new MeetFileUploadResponseDTO();
        dto.setFileId(fileUpload.getFileId());
        dto.setOriginalName(fileUpload.getOriginalName());
        dto.setFileSize(fileUpload.getFileSize());
        dto.setFileType(fileUpload.getFileType());
        dto.setUploaderId(fileUpload.getUploaderId());
        dto.setFilePath(fileUpload.getFilePath());
        dto.setFileUrl(fileUpload.getFileUrl());
        dto.setCreatedAt(fileUpload.getCreatedAt());
        dto.setUpdatedAt(fileUpload.getUpdatedAt());

        return dto;
    }

}
